const express = require('express')
const router = express.Router()
const pool = require('../utils/pool')

router.get('/datalist', (req, res, next) => {
  const sql = `
    select count(*) '楼宇数' from zh_properties;
    select count(*) '登记人口数' from zh_household;
    select count(*) '智能设备数' from zh_devices;
    select count(*) '智能设备数' from zh_devices;
    select count(*) '智能设备数' from zh_devices;
  `
  pool.query(sql, (err, result) => {
    if (err) {
      return next(err)
    }
    if(result.length === 0) {
      return res.send({
        code: 4001,
        msg: '查询失败'
      })
    }
    result = result.map(item => {
      const key = Object.keys(item[0])
      return {
        [key]: item[0][key]
      }
    })
    res.send({
      code: 2000,
      msg: '查询成功',
      data: result
    })
  })
})

// 获取图表数据
router.get('/chartdata', (req, res, next) => {
  const sql = `
  select decoration name, count(*) value from zh_properties group by decoration;
  select status name, count(*) value from zh_devices group by status;
  select type name, count(*) value from zh_devices group by type
  `
  pool.query(sql, (err, result) => {
    if (err) {
      return next(err)
    }
    if(result.length === 0) {
      return res.send({
        code: 4001,
        msg: '查询失败'
      })
    }
    res.send({
      code: 2000,
      msg: '查询成功',
      data: {
        decorationTypeChart: result[0],
        deviceStatusChart: result[1],
        deviceTypeChart: result[2],
      }
    })
  
  })
})

module.exports = router